﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Shell.KnowledgeBase
{
    public class Statement : Term, IEnumerable<Term>
    {
        private readonly IList<Term> _terms;

        public Statement(IEnumerable<Term> terms)
        {
            _terms = terms.ToArray();
        }

        public Statement(IList<Term> terms)
        {
            _terms = terms;
        }

        public int Length
        {
            get { return _terms.Count; }
        }

        public Term this[int index]
        {
            get { return _terms[index]; }
        }

        public IEnumerator<Term> GetEnumerator()
        {
            return _terms.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return _terms.GetEnumerator();
        }

        public override string ToString()
        {
            return string.Format(" ({0}) ",String.Join("", _terms.Select(_ => _.ToString())));
        }

        public Statement Resolve(BindingContext bindingContext)
        {
            return new Statement(
                _terms
                    .Select(_ =>
                            _ is Statement
                                ? ((Statement) _).Resolve(bindingContext)
                                : bindingContext.ResolveTerm(_))
                    .ToArray());
        }
    }
}